//
//  EncryptionData.m
//  DA_V
//
//  Created by 周季阳 on 15/5/13.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "EncryptionData.h"

@implementation EncryptionData

#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data :(NSString *)key{
    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",base64String);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [base64String length]; i++) {
        position = i % keyLength;
        strChar = [base64String characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
 
    return base64String1;
}

#pragma mark - 解密
-(NSString *)decryption:(NSString *)data :(NSString *)key{
    NSData* dataFromString1 = [[NSData alloc] initWithBase64EncodedString:data options:0];
    NSString* str1= [[NSString alloc] initWithData:dataFromString1  encoding:NSUTF8StringEncoding];
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [str1 length]; i++) {
        position = i % keyLength;
        strChar = [str1 characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* dataFromString = [[NSData alloc] initWithBase64EncodedString:result options:0];
    NSString* str= [[NSString alloc] initWithData:dataFromString  encoding:NSUTF8StringEncoding];

    return str;
}
@end
